package job;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pp.PowerProject;
import properties.AutoBGProperties;
import properties.BatchBGProperties;
import properties.User;
import util.EmailSender;
import util.HttpRequest;
import util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class BatchBG implements Job {
    private static final Logger logger = LoggerFactory.getLogger(BatchBG.class);
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final Random random = new Random();

    private BatchBGProperties properties;
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 20,
            1, TimeUnit.MINUTES, new ArrayBlockingQueue<>(20));

    public static void main(String[] args) {
        BatchBGProperties BatchBGProperties = new BatchBGProperties();
        BatchBG batchBG = new BatchBG();
        for (User user : BatchBGProperties.getUsers()) {
            batchBG.bg(user, args[0]);
        }
    }


    public BatchBG() {
        properties = new BatchBGProperties();
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        List<User> users = properties.getUsers();
        for (User user : users) {
            threadPoolExecutor.execute(() -> {
                bg(user);
            });
        }
    }

    public Object bg(User user, String firstDay) {
        HttpRequest httpRequest = new HttpRequest();
        PowerProject powerProject;
        AutoBGProperties autoBGProperties;
        if (user.getReportForWorkType().equalsIgnoreCase("all_auto")) {
            autoBGProperties = AutoBGProperties.newAllAutoProperties(user);
        } else {
            autoBGProperties = AutoBGProperties.readPropertiesByName(user);
        }
        if (StringUtils.isNotBlank(firstDay)) {
            autoBGProperties.setFirstDay(firstDay);
        }
        powerProject = new PowerProject(httpRequest, autoBGProperties);
        try {
            powerProject.login();
            String msg = powerProject.bg();
            EmailSender.send(true, "[" + sdf.format(new Date()) + "]执行报工成功:\n" + msg, user.getEmail());
        } catch (Exception e) {
            logger.error("用户[{}]执行报工异常", user.getName());
            e.printStackTrace();
            EmailSender.send(false, "[" + sdf.format(new Date()) + "]执行报工异常:\n" + e.getMessage(), user.getEmail());
        }
        return null;
    }


    public Object bg(User user) {
        return bg(user, null);
    }
}

